package de.piratech.dasding.data.database.couch;

import java.net.MalformedURLException;

import javax.annotation.PostConstruct;

import org.ektorp.CouchDbConnector;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import de.piratech.dasding.data.database.ActionData;
import de.piratech.dasding.data.database.Database;
import de.piratech.dasding.data.database.EventData;
import de.piratech.dasding.data.database.UserData;
import org.apache.commons.lang3.StringUtils;

@Service
public class CouchImpl implements Database {

  private static final Logger LOG = LoggerFactory.getLogger(CouchImpl.class);
  private CouchDbConnector couchDbConnector;
  private UserDataImpl userRepo;
  private EventDataImpl eventRepo;
  private ActionDataImpl actionRepo;
  @Value("${url}")
  private String url;
  @Value("${user}")
  private String userName;
  @Value("${password}")
  private String password;
  @Value("${database}")
  private String database;

  @PostConstruct
  private void init() throws MalformedURLException {
    LOG.debug("database {}", database);

    HttpClient authenticatedHttpClient =
            StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)
            ? new StdHttpClient.Builder().url(url).username(userName).password(password).build()
            : new StdHttpClient.Builder().url(url).build();
    StdCouchDbInstance couchDbInstance = new StdCouchDbInstance(
            authenticatedHttpClient);
    couchDbConnector = couchDbInstance.createConnector(database, false);
    userRepo = new UserDataImpl(couchDbConnector);
    eventRepo = new EventDataImpl(couchDbConnector);
    actionRepo = new ActionDataImpl(couchDbConnector);
  }

  @Override
  public UserData getUserData() {
    return userRepo;
  }

  @Override
  public EventData getEventData() {
    return eventRepo;
  }

  @Override
  public ActionData getActionData() {
    return actionRepo;
  }
}
